# from django.http import HttpResponse
import random

from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views import View
from django import http
import re
from django_redis import get_redis_connection

from meiduo_mall.libs.captcha.captcha import captcha

# Create your views here.
from meiduo_mall.libs.yuntongxun.sms import CCP
from meiduo_mall.utils.response_code import RET
from meiduo_mall.apps.verifications import contants


class ImageCodeView(View):
    def get(self, request, image_code_id):
        text, image_data = captcha.generate_captcha()

        #  将图片验证码保存到redis中

        redis_con = get_redis_connection("code")
        redis_con.setex("image_code_%s" % image_code_id, contants.REDIS_IMAGE_CODE_EXPIRES, text)

        return http.HttpResponse(image_data, content_type="image/png")


class SmsCodeView(View):
    def get(self, request, mobile):
        # 获取参数
        image_code = request.GET.get("image_code")
        image_code_id = request.GET.get("image_code_id")

        # 判断验证码
        if not all([image_code, image_code_id]):
            return http.JsonResponse({"errmsg": "请输入验证码", "code": RET.PARAMERR})

        redis_con = get_redis_connection("code")
        redis_image_code = redis_con.get("image_code_%s" % image_code_id)

        if not redis_image_code:
            return http.JsonResponse({"errmsg": "图片验证码已过期", "code": RET.PARAMERR})

        redis_con.delete("image_code_%s" % image_code_id)

        if image_code.lower() != redis_image_code.decode().lower():
            return http.JsonResponse({"errmsg": "验证号码输入错误", "code": RET.DATAERR})

        # if image_code.lower() != redis_image_code.decode().lower():
        #     return http.JsonResponse({"errmsg": "图片验证码错误", "code": RET.DATAERR})


        send_flag = redis_con.get("send_flag_%s" % mobile)
        if send_flag:
            return http.JsonResponse({"errmsg": "频繁发送", "code": RET.SMSCODERR})

        # 发送短信
        sms_code = "%06d" % random.randint(0, 999999)
        from celery_tasks.sms.task import send_sms_code
        print(sms_code)
        # send_sms_code(mobile, sms_code, contants.REDIS_SMS_CODE_EXPIRES/60)



        ccp = CCP()
        ccp.send_template_sms(mobile, [sms_code, contants.REDIS_SMS_CODE_EXPIRES/60], 1)

        pipeline = redis_con.pipeline()
        pipeline.setex("sms_code_%s" % mobile, contants.REDIS_SMS_CODE_EXPIRES, sms_code)
        pipeline.setex("send_flag_%s" % mobile, contants.REDIS_SEND_FLAG_EXPIRES, 1)
        pipeline.execute()
        # redis_con.setex("sms_code_%s" % mobile, contants.REDIS_SMS_CODE_EXPIRES, sms_code)
        # # redis_con.setex("send_flag_%s" % mobile, contants.REDIS_IMAGE_CODE_EXPIRES, True)
        # redis_con.setex("send_flag_%s" % mobile, contants.REDIS_SEND_FLAG_EXPIRES, True)

        return http.JsonResponse({"errmsg": "发送成功", "code": RET.OK})
